import pygame
import os
import sys 
# 添加父目录到系统路径，确保能找到constant模块
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)

# 使用绝对导入代替相对导入
from constant import Setting

class Button:
    """支持背景图片的游戏按钮类"""
    
    def __init__(self, x, y, width=None, height=None, text="", 
                 settings=None, is_small=False, action=None, 
                 image_path=None):  # 新增：图片路径参数
        # 使用提供的设置或创建新设置
        self.settings = settings if settings else Setting()
        
        # 按钮尺寸
        if is_small:
            self.width = width if width else self.settings.btn_small_width
            self.height = height if height else self.settings.btn_small_height
        else:
            self.width = width if width else self.settings.btn_width
            self.height = height if height else self.settings.btn_height
            
        # 按钮位置和区域
        self.rect = pygame.Rect(x, y, self.width, self.height)
        
        # 按钮状态
        self.is_hovered = False
        self.is_pressed = False
        self.action = action  # 点击时执行的函数
        
        # 加载按钮背景图片（如果提供）
        self.background_image = None
        self._load_background_image(image_path)
        
        # 按钮文本
        self.text = text
        self._update_text_surface()
    
    def _load_background_image(self, image_path):
        """加载并调整按钮背景图片"""
        if not image_path:
            return  # 没有提供图片路径则不加载
        
        try:
            # 加载图片并调整大小以适应按钮
            self.background_image = pygame.image.load(image_path).convert_alpha()
            self.background_image = pygame.transform.scale(
                self.background_image, 
                (self.width, self.height)
            )
        except FileNotFoundError:
            print(f"警告：找不到按钮背景图片 {image_path}，将使用默认样式")
    
    def _update_text_surface(self):
        """更新按钮上的文本表面（支持多行）"""
        self.text_surfaces = []
        self.text_rects = []

        # 按换行符分割文本为多行
        lines = self.text.split('\n')

        # 计算总文本高度（行高 * 行数）
        line_height = self.settings.font_menu.size('Tg')[1]  # 获取单行高度
        total_height = line_height * len(lines)

        # 计算第一行文本的起始Y坐标（使整体居中）
        start_y = self.rect.centery - (total_height // 2)

        for i, line in enumerate(lines):
            # 渲染单行文本
            text_surface = self.settings.font_menu.render(line, True, self.settings.btn_text_color)
            text_rect = text_surface.get_rect(centerx=self.rect.centerx)  # 水平居中
            text_rect.y = start_y + i * line_height  # 垂直方向按行偏移

            self.text_surfaces.append(text_surface)
            self.text_rects.append(text_rect)
    
    def set_text(self, new_text):
        """设置按钮文本"""
        self.text = new_text
        self._update_text_surface()
    
    def handle_event(self, event):
        """处理与按钮相关的事件"""
        if event.type == pygame.MOUSEMOTION:
            # 检测鼠标是否悬停在按钮上
            self.is_hovered = self.rect.collidepoint(event.pos)
            self.is_pressed = False  # 鼠标移动时取消按下状态
            
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # 检测鼠标按下
            if event.button == 1 and self.rect.collidepoint(event.pos):
                self.is_pressed = True
                
        elif event.type == pygame.MOUSEBUTTONUP:
            # 检测鼠标释放（点击完成）
            if event.button == 1 and self.is_pressed and self.rect.collidepoint(event.pos):
                self.is_pressed = False
                # 执行按钮动作
                if self.action:
                    self.action()
    
    def draw(self, screen):
        """在屏幕上绘制按钮（支持多行文本）"""
        # 1. 绘制背景图片（如果有）
        if self.background_image:
            # 保持原有的背景图片绘制逻辑不变
            if self.is_pressed:
                temp_surf = self.background_image.copy()
                temp_surf.set_alpha(200)
                screen.blit(temp_surf, self.rect)
            elif self.is_hovered:
                screen.blit(self.background_image, self.rect)
            else:
                temp_surf = self.background_image.copy()
                temp_surf.set_alpha(230)
                screen.blit(temp_surf, self.rect)
        else:
            # 2. 没有背景图片时使用默认颜色样式
            if self.is_pressed:
                color = self.settings.btn_pressed_color
            elif self.is_hovered:
                color = self.settings.btn_hover_color
            else:
                color = self.settings.btn_normal_color
            
            pygame.draw.rect(screen, color, self.rect, border_radius=self.settings.btn_radius)
        
        # 3. 绘制多行文本（替换原有的单行文本绘制）
        for surface, rect in zip(self.text_surfaces, self.text_rects):
            screen.blit(surface, rect)
    
    def is_clicked(self, pos):
        """检查指定位置是否在按钮区域内"""
        return self.rect.collidepoint(pos)